/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * AdminRegCliente.java
 *
 * Created on 19-sep-2009, 1:15:30
 */

package com.jomijushi.fid.interfaz;

import com.jomijushi.fid.dominio.FidCliente;
import com.jomijushi.fid.dominio.FidTipoCliente;
import com.jomijushi.fid.servicios.PersonaEmpresaImplementsService;
import com.jomijushi.fid.servicios.PersonaEmpresaInterfazService;
import java.util.Date;
import java.util.List;
import javax.persistence.EntityManager;
import javax.swing.JOptionPane;

/**
 *
 * @author miguel
 */
public class AdminRegCliente extends javax.swing.JDialog {

    List<FidTipoCliente> lst=null;
    String error="";
    public boolean cancelado=false;
    public boolean guardado=false;
    public int documentoSelect=1;
    
    /** Creates new form AdminRegCliente */
    public AdminRegCliente(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        this.setLocationRelativeTo(this);
        LlenarComboTipoCliente();
    }

    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        nombres = new javax.swing.JTextField();
        labeldniruc = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        documento = new javax.swing.JTextField();
        email = new javax.swing.JTextField();
        telefono = new javax.swing.JTextField();
        nacimiento = new com.toedter.calendar.JDateChooser();
        direccion = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        descripcion = new javax.swing.JTextArea();
        jLabel9 = new javax.swing.JLabel();
        tipo_documento = new javax.swing.JComboBox();
        jLabel10 = new javax.swing.JLabel();
        tipo_cliente = new javax.swing.JComboBox();
        BotonGuardar = new javax.swing.JButton();
        BotonRestablecer = new javax.swing.JButton();
        BotonCancelar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Registrar Cliente");

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos Generales"));

        jLabel1.setText("Nombres:");

        nombres.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                nombresKeyTyped(evt);
            }
        });

        labeldniruc.setText("DNI:");

        jLabel3.setText("Email:");

        jLabel4.setText("Teléfono:");

        jLabel5.setText("Nacimiento:");

        jLabel6.setText("Domicilio:");

        jLabel7.setText("Descripción:");

        documento.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                documentoKeyTyped(evt);
            }
        });

        telefono.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                telefonoKeyTyped(evt);
            }
        });

        nacimiento.setDateFormatString("dd/MM/yyyy");
        nacimiento.setMaxSelectableDate(new java.util.Date(253370786462000L));
        nacimiento.setMinSelectableDate(new java.util.Date(-62135747938000L));

        direccion.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                direccionKeyTyped(evt);
            }
        });

        descripcion.setColumns(20);
        descripcion.setFont(new java.awt.Font("Tahoma", 0, 11));
        descripcion.setLineWrap(true);
        descripcion.setRows(5);
        descripcion.setWrapStyleWord(true);
        jScrollPane1.setViewportView(descripcion);

        jLabel9.setText("Documento:");

        tipo_documento.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "DNI", "RUC" }));
        tipo_documento.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                tipo_documentoItemStateChanged(evt);
            }
        });

        jLabel10.setText("Tipo Cliente:");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(13, 13, 13)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel9)
                            .addComponent(jLabel1)
                            .addComponent(labeldniruc)
                            .addComponent(jLabel3)
                            .addComponent(jLabel4))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(tipo_documento, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(nombres, javax.swing.GroupLayout.PREFERRED_SIZE, 269, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(documento, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(email, javax.swing.GroupLayout.PREFERRED_SIZE, 202, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(telefono, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(13, 13, 13)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(jLabel6)
                                    .addComponent(jLabel7)
                                    .addComponent(jLabel5)))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addContainerGap()
                                .addComponent(jLabel10)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(direccion, javax.swing.GroupLayout.DEFAULT_SIZE, 312, Short.MAX_VALUE)
                            .addComponent(nacimiento, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 312, Short.MAX_VALUE)
                            .addComponent(tipo_cliente, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(nombres, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel9)
                    .addComponent(tipo_documento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(documento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(labeldniruc))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(email, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(telefono, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(nacimiento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(direccion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel7))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(tipo_cliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel10))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        BotonGuardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/disk.png"))); // NOI18N
        BotonGuardar.setText("Guardar");
        BotonGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BotonGuardarActionPerformed(evt);
            }
        });

        BotonRestablecer.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/arrow_undo.png"))); // NOI18N
        BotonRestablecer.setText("Restablecer");
        BotonRestablecer.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BotonRestablecerActionPerformed(evt);
            }
        });

        BotonCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/cancel.png"))); // NOI18N
        BotonCancelar.setText("Cancelar");
        BotonCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BotonCancelarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(BotonGuardar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(BotonRestablecer)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(BotonCancelar)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(BotonCancelar)
                    .addComponent(BotonGuardar)
                    .addComponent(BotonRestablecer))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void nombresKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_nombresKeyTyped
        // TODO add your handling code here:
        SoloTexto(evt);
}//GEN-LAST:event_nombresKeyTyped

    private void documentoKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_documentoKeyTyped
        // TODO add your handling code here:
        if(documentoSelect==1){
            if(documento.getText().length()<8){
                SoloDigito(evt);
            } else{
                evt.consume();
            }
        }
        else if(documentoSelect==2){
            if(documento.getText().length()<11){
                SoloDigito(evt);
            } else{
                evt.consume();
            }
        }

}//GEN-LAST:event_documentoKeyTyped

    private void telefonoKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_telefonoKeyTyped
        // TODO add your handling code here:
        SoloDigito(evt);
}//GEN-LAST:event_telefonoKeyTyped

    private void direccionKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_direccionKeyTyped
        // TODO add your handling code here:
        //SoloTexto(evt);
}//GEN-LAST:event_direccionKeyTyped

    private void BotonGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BotonGuardarActionPerformed
        // TODO add your handling code here:
        if(validado())// Los datos son correctos y seran almacenados
        {
            PersonaEmpresaInterfazService clienteService = new PersonaEmpresaImplementsService();
            FidCliente ft= new FidCliente();

            ft.setNombres(nombres.getText());
            ft.setDniRuc(documento.getText());
            ft.setEmail(email.getText());
            ft.setTelefono(telefono.getText());
            ft.setFechaNac(nacimiento.getDate());
            ft.setDireccion(direccion.getText());
            ft.setDescripcion(descripcion.getText());
            ft.setCreatedAt(new Date());
            ft.setUpdatedAt(new Date());

            boolean termino=false;
            for(int i=0; i<lst.size() && !termino ; i++){
                if(lst.get(i).getNombre().compareTo(tipo_cliente.getSelectedItem().toString())==0){
                    ft.setFidTipoClienteId(lst.get(i));
                    termino=true;
                }
            }
            clienteService.setEntityManagerFactory(PanelPrincipal.emf);
            //clienteService.crearPersonaEmpresa(ft);
            clienteService.registrar(ft);
            JOptionPane.showMessageDialog(this, "Cliente Registrado Correctamente", "Registrar Trabajador", JOptionPane.INFORMATION_MESSAGE);
            guardado=true;
            this.setVisible(false);
        } else
            JOptionPane.showMessageDialog(this, error, "Error", JOptionPane.WARNING_MESSAGE);
}//GEN-LAST:event_BotonGuardarActionPerformed

    private void BotonRestablecerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BotonRestablecerActionPerformed
        // TODO add your handling code here:
        Restablecer();
}//GEN-LAST:event_BotonRestablecerActionPerformed

    private void BotonCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BotonCancelarActionPerformed
        // TODO add your handling code here:
        this.setVisible(false);
        cancelado=true;
}//GEN-LAST:event_BotonCancelarActionPerformed

    private void tipo_documentoItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_tipo_documentoItemStateChanged
        // TODO add your handling code here:
        String escogido=evt.getItem().toString();
        if(escogido.compareTo("DNI")==0){
            labeldniruc.setText("DNI:");
            documentoSelect=1;
        }else if(escogido.compareTo("RUC")==0){
            labeldniruc.setText("RUC:");
            documentoSelect=2;
        }
    }//GEN-LAST:event_tipo_documentoItemStateChanged

    public void Restablecer()
    {
        nombres.setText("");
        documento.setText("");
        email.setText("");
        telefono.setText("");
        nacimiento.setDate(null);
        direccion.setText("");
        descripcion.setText("");        
    }

    public void LlenarComboTipoCliente()
    {
        EntityManager em = PanelPrincipal.emf.createEntityManager();
        lst= em.createQuery("SELECT f FROM FidTipoCliente f ORDER BY f.nombre")
               .getResultList();
        for(int i=0; i<lst.size(); i++){
            tipo_cliente.addItem(lst.get(i).getNombre());
        }        
    }

    public boolean validado()
    {
        error="";
        if(nombres.getText().length()==0)
            error+="- Ingrese Nombres\n";
        if(documentoSelect==1){
            if(documento.getText().length()!=8)
            {
                error+="- Ingrese DNI (8 digitos)\n";
                System.out.println("Es igual a 8 entro el DNI");
            }
        } else if(documentoSelect==2){
            if(documento.getText().length()!=11)
                error+="- Ingrese RUC (11 digitos)\n";
            System.out.println("Es igual a 11 entro el RUC");
        }
        if(error.length()==0)
            return true;
        return false;
    }

    private void SoloTexto(java.awt.event.KeyEvent evt)
    {
        char c=evt.getKeyChar();
        if(Character.isDigit(c))
            evt.consume();
    }

    private void SoloDigito(java.awt.event.KeyEvent evt)
    {
        char c=evt.getKeyChar();
        if(!Character.isDigit(c))
            evt.consume();
    }
    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                AdminRegCliente dialog = new AdminRegCliente(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton BotonCancelar;
    private javax.swing.JButton BotonGuardar;
    private javax.swing.JButton BotonRestablecer;
    private javax.swing.JTextArea descripcion;
    private javax.swing.JTextField direccion;
    private javax.swing.JTextField documento;
    private javax.swing.JTextField email;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel labeldniruc;
    private com.toedter.calendar.JDateChooser nacimiento;
    private javax.swing.JTextField nombres;
    private javax.swing.JTextField telefono;
    private javax.swing.JComboBox tipo_cliente;
    private javax.swing.JComboBox tipo_documento;
    // End of variables declaration//GEN-END:variables

}
